package com.db.client;

import com.db.exceptions.BadInputConnectionException;
import com.db.exceptions.BadServerResponseException;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.util.LinkedList;
import java.util.List;
import java.util.StringTokenizer;

public class ChatPrinter extends Thread {

    private ObjectInputStream inputConnection;
    private UI ui;

    public ChatPrinter(ObjectInputStream inputConnection, UI ui) throws BadInputConnectionException {
        //why error?!
        if (inputConnection == null) throw new BadInputConnectionException();
        setDaemon(true);
        this.inputConnection = inputConnection;
        this.ui = ui;
    }

    @Override
    public void run() {
        Object input;
        while (!isInterrupted()) {
            try {
                input = inputConnection.readObject();

                //waiting for string
                if (!(input instanceof String)) throw new BadServerResponseException();

                //string may be interpreted several ways
                //String[] messages = (String[])(parseRespond((String)input).toArray());

                //Console knows what to do
                ui.printMessages((String)input);

            } catch (ClassNotFoundException | IOException e) {
                this.interrupt();
                ui.error("--- server response fail ---");
            } catch (BadServerResponseException e) {
                ui.error("--- bad server response ---");
            }
        }
    }

    private List<String> parseRespond(String respond) {
        StringTokenizer tokenizer = new StringTokenizer(respond, "\n");
        List<String> lines = new LinkedList<>();
        for (int i = 0, num = tokenizer.countTokens(); i < num; ++i) {
            lines.add(tokenizer.nextToken());
        }
        return lines;
    }
}
